﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreShop.App
{
    class FoodImgService
    {
        /// <summary>
        /// 删除文件夹下的所有文件信息
        /// </summary>
        /// <param name="sourceFilePath"></param>
        public static void DeleteFolder(string sourceFilePath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(sourceFilePath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }


        #region 压缩图片

        /// <summary>
        /// 保存为JPEG格式，支持压缩质量选项
        /// </summary>
        /// <param name="bmp">原始位图</param>
        /// <param name="FileName">新文件地址</param>
        /// <param name="Qty">压缩质量，越大越好，文件也越大(0-100)</param>
        /// <returns>成功标志</returns>
        public static bool SaveAsJPEG(Bitmap bmp, string FileName, int Qty)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
                ps.Param[0] = p;

                bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 保存为JPEG格式，支持压缩质量选项
        /// </summary>
        /// <param name="bmp">原始位图</param>
        /// <param name="FileName">新文件地址</param>
        /// <param name="Qty">压缩质量，越大越好，文件也越大(0-100)</param>
        /// <returns>成功标志</returns>
        public static bool SaveAsFormat(Bitmap bmp, ImageFormat format, string FileName, int Qty)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
                ps.Param[0] = p;

                bmp.Save(FileName, format);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 保存JPG时用
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns>得到指定mimeType的ImageCodecInfo</returns>
        public static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        public static bool IsLargeImage(string sourcePath)
        {
            Image sourceImage = Image.FromFile(sourcePath);
            try
            {
                int mWidth = sourceImage.Width;
                int mHeight = sourceImage.Height;
                if ((mWidth > 400) || (mHeight > 400)) return true;

                return false;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return false;
            }
            finally
            {
                sourceImage.Dispose();
                sourceImage = null;
                GC.Collect();
            }
        }


        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool CompressPicture(string sourcePath)
        {
            string targetPath = sourcePath;
            if (IsLargeImage(sourcePath))
            {
                try
                {
                    string path = Path.GetDirectoryName(sourcePath) + @"\Temp";
                    string newPath = path + @"\" + Path.GetFileName(sourcePath);
                    string oldPath = targetPath;
                    //判断移动的文件夹是否存在,不存在则创建
                    if (Directory.Exists(path))
                    {
                        //先删除再移动
                        File.Delete(newPath);
                        File.Move(oldPath, newPath);
                    }
                    else
                    {
                        Directory.CreateDirectory(path);
                        File.Move(oldPath, newPath);
                    }
                    sourcePath = newPath;
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                    return false;
                }
            }

            try
            {
                Image sourceImage = Image.FromFile(sourcePath);

                //调整图片大小
                Bitmap bmp = new Bitmap(sourceImage, new Size(200, 200));
                //压缩图片
                SaveAsJPEG(bmp, targetPath, 100);
                bmp.Dispose();
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 压缩图片Jpg
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool CompressGoodsImg(string sourcePath, string targetPath, string imgTag)
        {
            try
            {
                Image sourceImage = Image.FromFile(sourcePath);

                //调整图片大小
                Bitmap bmp = new Bitmap(sourceImage, new Size(200, 200));
                //压缩图片
                if (imgTag == "jpg")
                {
                    SaveAsJPEG(bmp, targetPath, 100);
                }
                else if (imgTag == "png")
                {
                    SaveAsFormat(bmp, ImageFormat.Png, targetPath, 100);
                }
                else if (imgTag == "jpeg")
                {
                    SaveAsFormat(bmp, ImageFormat.Jpeg, targetPath, 100);
                }
                bmp.Dispose();
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return false;
            }
        }


        /// <summary>
        /// 压缩本地图片
        /// </summary>
        public static void SetCompressLocaleImg()
        {
            Thread newThread = new Thread(() => CompressLocaleImg(), 1024 * 512);
            newThread.Name = String.Format("Thread{0}", DateTime.Now.ToString());
            newThread.Start();
        }

        public static int GetFileCount(string path, string ext)
        {
            int FileCount = 0;
            if (!Directory.Exists(path)) return FileCount;
            DirectoryInfo Dir = new DirectoryInfo(path);
            foreach (FileInfo FI in Dir.GetFiles())
            {
                // 这里写文件格式
                if (System.IO.Path.GetExtension(FI.Name) == ext)
                {
                    FileCount++;
                }
            }
            return FileCount;
        }

        /// <summary>
        /// 压缩后台的图片
        /// </summary>
        public static void SetCompressGoodsImg()
        {
            try
            {
                string path = System.Windows.Forms.Application.StartupPath + "\\foodimg";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                int count_max = System.IO.Directory.GetFiles(path).Length;

                path = System.Windows.Forms.Application.StartupPath + "\\foodimg\\icons";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                int count_min = System.IO.Directory.GetFiles(path).Length;

                if ((count_max == 0) || (count_min >= count_max)) return;

                Thread newThread = new Thread(() => CompressGoodsImg(), 1024 * 512);
                newThread.IsBackground = true;
                newThread.Name = String.Format("Thread{0}", DateTime.Now.ToString());
                newThread.Start();
            }
            catch { }
        }

        public static void CompressLocaleImg()
        {

            if (AppConstVars.files_LocaleImgs == null) return;
            try
            {
                foreach (string file in AppConstVars.files_LocaleImgs)
                {
                    CompressPicture(file);
                }
            }
            catch { }
        }

        public static void CompressGoodsImg()
        {
            string sFilePath = System.Windows.Forms.Application.StartupPath + "\\foodimg";
            FolderBrowserDialog fbd_goodsimg = new FolderBrowserDialog();
            fbd_goodsimg.SelectedPath = sFilePath;
            AppConstVars.files_GoodsImgs = Directory.GetFiles(fbd_goodsimg.SelectedPath, "*.jpg");
            var iconsPath = System.Windows.Forms.Application.StartupPath + "\\foodimg\\icons";
            string targetPath = "";
            int iconCount = 0;
            if (AppConstVars.files_GoodsImgs.Length > 0)
            {
                iconCount = GetFileCount(iconsPath, ".jpg");
                if (iconCount != AppConstVars.files_GoodsImgs.Length)
                {
                    try
                    {
                        foreach (string file in AppConstVars.files_GoodsImgs)
                        {
                            targetPath = Path.GetDirectoryName(file) + "\\icons\\" + Path.GetFileName(file);
                            if (!File.Exists(targetPath))
                            {
                                CompressGoodsImg(file, targetPath, "jpg");
                            }
                        }
                    }
                    catch { }
                }
            }

            AppConstVars.files_GoodsImgs = Directory.GetFiles(fbd_goodsimg.SelectedPath, "*.png");
            if (AppConstVars.files_GoodsImgs.Length > 0)
            {
                iconCount = GetFileCount(iconsPath, ".png");
                if (iconCount != AppConstVars.files_GoodsImgs.Length)
                {
                    try
                    {
                        foreach (string file in AppConstVars.files_GoodsImgs)
                        {
                            targetPath = Path.GetDirectoryName(file) + "\\icons\\" + Path.GetFileName(file);
                            if (!File.Exists(targetPath))
                            {
                                CompressGoodsImg(file, targetPath, "png");
                            }
                        }
                    }
                    catch { }
                }
            }

            AppConstVars.files_GoodsImgs = Directory.GetFiles(fbd_goodsimg.SelectedPath, "*.jpeg");
            if (AppConstVars.files_GoodsImgs.Length > 0)
            {
                iconCount = GetFileCount(iconsPath, ".jpeg");
                if (iconCount != AppConstVars.files_GoodsImgs.Length)
                {
                    try
                    {
                        foreach (string file in AppConstVars.files_GoodsImgs)
                        {
                            targetPath = Path.GetDirectoryName(file) + "\\icons\\" + Path.GetFileName(file);
                            if (!File.Exists(targetPath))
                            {
                                CompressGoodsImg(file, targetPath, "jpeg");
                            }
                        }
                    }
                    catch { }
                }
            }
        }

        #endregion

    }
}
